#!/usr/bin/env python
# encoding: utf-8
# @Time    : 2020/9/2 11:09
# @Author  : Mr. Cui
# @File    : framework.py
# @Software: PyCharm
import collections

from flask import jsonify
import datetime
import time


def result(code, message=None, data=None):
    """
    为视图函数构造返回数据结构
    :param data:
    :param code: code码
    :param message: 前端选择性展示
    :return:{'error': {'code': 1001, 'message': '无效的会话', 'data': {}}}
    """
    if data is None:
        data = {}
    if message is None:
        message = ""
    return jsonify({"code": code, "message": str(message), "data": data})


def result_msg(code, msg=None):
    """
    为视图函数构造返回数据结构
    :param code: code码
    :param msg: 前端选择性展示
    :return:{'error': {'code': 1001, 'message': '无效的会话', 'data': {}}}
    """
    if msg is None:
        msg = ""
    return jsonify({"code": code, "msg": str(msg)})


def date_format_ymd(date, format_type, day):
    """
    操作时间并进行格式化
    :param date: 指定时间
    :param format_type: 格式化类型
    :param day: 操作加减时间：hours=1
    :return: 格式化后时间
    """
    return (datetime.datetime.strptime(date, '%Y-%m-%d') + datetime.timedelta(days=day)).__format__(
        format_type)


def date_format_h(date, format_type, hour):
    """
    操作时间并进行格式化
    :param date: 指定时间
    :param format_type: 格式化类型
    :param hour: 操作加减时间：days=1
    :return: 格式化后时间
    """
    return (datetime.datetime.strptime(date, '%Y-%m-%d %H') + datetime.timedelta(hours=hour)).__format__(
        format_type)


def timestamp_to_hms(seconds):
    """
    秒数转化成时间格式
    :param seconds:
    :return:
    """
    m, s = divmod(seconds, 60)
    h, m = divmod(m, 60)
    return "%02d小时%02d分%02d秒" % (h, m, s)


def ymdhms_to_timestamp(str_time):
    """
    字符串时间格式转化成秒数时间戳
    :param str_time: "2019-5-10 23:40:00"
    :return: 秒数时间戳
    """
    # 先转换为时间数组
    timeArray = time.strptime(str_time, "%Y-%m-%d %H:%M:%S")
    # 转换为时间戳
    return int(time.mktime(timeArray))


def sort_listdic(listdic):
    """
    list包含字典排序
    :return:
    """
    return collections.OrderedDict(sorted(listdic.items(), key=lambda t: t[1]))


def list_include_dic(l1, l2):
    """
     list包含字典
    :param l1: key的数组
    :param l2: value的数组
    :return: list包含字典
    """
    if len(l1) == len(l2):
        list_i_dic = {}
        for i in range(len(l1)):
            list_i_dic[l1[i]] = l2[i]
        return list_i_dic
    else:
        raise Exception(print("两个集合的长度不一致"))

def trans_format(time_string, from_format, to_format='%Y.%m.%d'):
    """
    @note 时间格式转化
    :param time_string:
    :param from_format:
    :param to_format:
    :return:
    """
    time_struct = time.strptime(time_string,from_format)
    times = time.strftime(to_format, time_struct)
    return times
